<template>
  <div class="publish-post">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="发布帖子"
      left-text="取消"
      right-text="发布"
      left-arrow
      @click-left="handleCancel"
      @click-right="handlePublish"
    />

    <div class="publish-container">
      <!-- 分类选择 -->
      <div class="form-section">
        <div class="section-title">选择分类</div>
        <van-field
          v-model="categoryText"
          label="问题分类"
          placeholder="请选择问题分类"
          readonly
          is-link
          required
          @click="showCategoryPicker = true"
        />
      </div>

      <!-- 标题输入 -->
      <div class="form-section">
        <div class="section-title">标题</div>
        <van-field
          v-model="form.title"
          placeholder="简要描述您的问题（10-50字）"
          maxlength="50"
          show-word-limit
          required
        />
      </div>

      <!-- 内容输入 -->
      <div class="form-section">
        <div class="section-title">详细描述</div>
        <van-field
          v-model="form.content"
          type="textarea"
          placeholder="请详细描述您遇到的问题，包括时间、地点、经过等信息，这将有助于其他用户为您提供更准确的建议..."
          rows="8"
          maxlength="2000"
          show-word-limit
          required
        />
      </div>

      <!-- 图片上传 -->
      <div class="form-section">
        <div class="section-title">上传图片（可选）</div>
        <div class="image-upload">
          <div class="uploaded-images">
            <div
              v-for="(image, index) in uploadedImages"
              :key="index"
              class="image-item"
            >
              <img :src="image.url" class="uploaded-image" />
              <div class="image-remove" @click="removeImage(index)">
                <van-icon name="cross" />
              </div>
            </div>
            <div
              v-if="uploadedImages.length < 9"
              class="upload-btn"
              @click="selectImages"
            >
              <van-icon name="photograph" />
              <span>添加图片</span>
            </div>
          </div>
          <div class="upload-tip">最多可上传9张图片，支持jpg、png格式</div>
        </div>
      </div>

      <!-- 标签输入 -->
      <div class="form-section">
        <div class="section-title">添加标签（可选）</div>
        <div class="tags-input">
          <div class="selected-tags">
            <span
              v-for="(tag, index) in selectedTags"
              :key="index"
              class="tag-item"
            >
              {{ tag }}
              <van-icon name="cross" @click="removeTag(index)" />
            </span>
          </div>
          <van-field
            v-model="tagInput"
            placeholder="输入标签后按回车添加"
            @keyup.enter="addTag"
          />
          <div class="suggested-tags">
            <div class="suggested-title">推荐标签：</div>
            <div class="tag-suggestions">
              <span
                v-for="tag in suggestedTags"
                :key="tag"
                class="suggested-tag"
                @click="addSuggestedTag(tag)"
              >
                {{ tag }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 涉及金额 -->
      <div class="form-section">
        <div class="section-title">涉及金额（可选）</div>
        <van-field
          v-model="form.involvedAmount"
          type="number"
          placeholder="如有涉及金额，请填写"
          left-icon="gold-coin-o"
        />
      </div>

      <!-- 发生时间 -->
      <div class="form-section">
        <div class="section-title">问题发生时间（可选）</div>
        <van-field
          v-model="form.occurTime"
          placeholder="请选择问题发生时间"
          readonly
          is-link
          @click="showDatePicker = true"
        />
      </div>

      <!-- 发生地点 -->
      <div class="form-section">
        <div class="section-title">发生地点（可选）</div>
        <van-field
          v-model="form.location"
          placeholder="请输入问题发生的地点"
          left-icon="location-o"
        />
      </div>

      <!-- 匿名发布 -->
      <div class="form-section">
        <van-cell title="匿名发布" center>
          <template #right-icon>
            <van-switch v-model="form.isAnonymous" />
          </template>
        </van-cell>
        <div class="anonymous-tip">
          开启后，您的昵称和头像将不会显示，但仍可正常接收回复通知
        </div>
      </div>

      <!-- 发布按钮 -->
      <div class="publish-actions">
        <van-button
          type="primary"
          size="large"
          :loading="publishing"
          :disabled="!canPublish"
          @click="handlePublish"
        >
          {{ publishing ? '发布中...' : '发布帖子' }}
        </van-button>
      </div>
    </div>

    <!-- 分类选择器 -->
    <van-popup v-model:show="showCategoryPicker" position="bottom">
      <van-picker
        :columns="categoryOptions"
        @confirm="onCategoryConfirm"
        @cancel="showCategoryPicker = false"
      />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-if="showDatePicker"
        v-model="currentDate"
        @confirm="onDateConfirm"
        @cancel="onDateCancel"
      />
    </van-popup>

    <!-- 图片选择器 -->
    <input
      ref="imageInput"
      type="file"
      accept="image/*"
      multiple
      style="display: none"
      @change="handleImageSelect"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { useUserStore } from '@/stores/user'
import { publishPost } from '@/api/community'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const form = reactive({
  title: '',
  content: '',
  categoryId: null,
  involvedAmount: '',
  occurTime: '',
  location: '',
  isAnonymous: false
})

const uploadedImages = ref([])
const selectedTags = ref([])
const tagInput = ref('')
const publishing = ref(false)
const showCategoryPicker = ref(false)
const showDatePicker = ref(false)
const currentDate = ref(new Date())
const imageInput = ref(null)

// 分类选项
const categoryOptions = [
  { text: '职场纠纷', value: 1 },
  { text: '消费维权', value: 2 },
  { text: '租房矛盾', value: 3 },
  { text: '其他问题', value: 4 }
]

// 推荐标签
const suggestedTags = ref([
  '工资拖欠', '劳动合同', '工伤赔偿', '违法解除',
  '押金纠纷', '房屋维修', '租金上涨', '提前退租',
  '商品质量', '虚假宣传', '退款纠纷', '售后服务',
  '合同纠纷', '欺诈行为', '维权经验', '法律咨询'
])

// 计算属性
const categoryText = computed(() => {
  const category = categoryOptions.find(item => item.value === form.categoryId)
  return category ? category.text : '请选择问题分类'
})

const canPublish = computed(() => {
  return form.title.trim() && 
         form.content.trim() && 
         form.categoryId && 
         !publishing.value
})

// 方法
const handleCancel = async () => {
  // 检查是否有未保存的内容
  const hasContent = form.title.trim() || 
                    form.content.trim() || 
                    uploadedImages.value.length > 0 ||
                    selectedTags.value.length > 0

  if (hasContent) {
    try {
      await showConfirmDialog({
        title: '确认离开',
        message: '您有未保存的内容，确定要离开吗？'
      })
      router.go(-1)
    } catch (error) {
      // 用户取消
    }
  } else {
    router.go(-1)
  }
}

const handlePublish = async () => {
  if (!canPublish.value) {
    if (!form.title.trim()) {
      showToast('请输入标题')
      return
    }
    if (!form.content.trim()) {
      showToast('请输入详细描述')
      return
    }
    if (!form.categoryId) {
      showToast('请选择问题分类')
      return
    }
    return
  }

  publishing.value = true

  try {
    // 构建发布数据，严格按照后端DTO字段
    const publishData = {
      title: form.title.trim(),
      content: form.content.trim(),
      category: form.categoryId, // 注意：后端DTO字段名是category，不是categoryId
      tags: selectedTags.value.join(','),
      isAnonymous: form.isAnonymous,
      status: 0 // 默认状态：待解决
    }

    console.log('发布数据:', publishData)

    const response = await publishPost(publishData)
    
    if (response.code === 200) {
      showToast('发布成功')
      // 跳转到帖子详情页
      router.replace(`/community/post/${response.data.id}`)
    } else {
      showToast(response.message || '发布失败')
    }
  } catch (error) {
    console.error('发布帖子失败:', error)
    showToast('发布失败，请重试')
  } finally {
    publishing.value = false
  }
}

const onCategoryConfirm = (value) => {
  if (value && value.selectedOptions && value.selectedOptions.length > 0) {
    form.categoryId = value.selectedOptions[0].value
  } else if (value && value.selectedValues && value.selectedValues.length > 0) {
    form.categoryId = value.selectedValues[0]
  }
  showCategoryPicker.value = false
  
  // 根据分类更新推荐标签
  updateSuggestedTags(form.categoryId)
}

const onDateConfirm = (value) => {
  try {
    let dateStr = ''
    
    // 处理不同格式的日期值
    if (value && typeof value === 'object') {
      if (Array.isArray(value.selectedValues) && value.selectedValues.length >= 3) {
        const year = value.selectedValues[0]
        const month = value.selectedValues[1]
        const day = value.selectedValues[2]
        dateStr = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
      } else if (value instanceof Date) {
        dateStr = value.toISOString().split('T')[0]
      } else if (value.getFullYear) {
        dateStr = value.toISOString().split('T')[0]
      }
    } else if (currentDate.value) {
      dateStr = currentDate.value.toISOString().split('T')[0]
    }
    
    if (dateStr) {
      form.occurTime = dateStr
    } else {
      form.occurTime = new Date().toISOString().split('T')[0]
    }
  } catch (error) {
    console.error('日期选择器错误:', error)
    form.occurTime = new Date().toISOString().split('T')[0]
  }
  showDatePicker.value = false
}

const onDateCancel = () => {
  showDatePicker.value = false
}

const selectImages = () => {
  imageInput.value.click()
}

const handleImageSelect = async (event) => {
  const files = Array.from(event.target.files)
  if (files.length === 0) return

  // 检查图片数量限制
  if (uploadedImages.value.length + files.length > 9) {
    showToast('最多只能上传9张图片')
    return
  }

  // 检查文件大小和格式
  for (const file of files) {
    if (file.size > 5 * 1024 * 1024) {
      showToast('图片大小不能超过5MB')
      return
    }
    
    if (!file.type.startsWith('image/')) {
      showToast('只能上传图片文件')
      return
    }
  }

  // 模拟上传过程
  showToast('正在上传图片...')
  
  try {
    // 这里应该调用实际的图片上传接口
    // 现在先模拟生成URL
    for (const file of files) {
      const url = URL.createObjectURL(file)
      uploadedImages.value.push({
        file,
        url,
        name: file.name
      })
    }
    
    showToast('图片上传成功')
  } catch (error) {
    console.error('图片上传失败:', error)
    showToast('图片上传失败')
  }

  // 清空input
  event.target.value = ''
}

const removeImage = (index) => {
  uploadedImages.value.splice(index, 1)
}

const addTag = () => {
  const tag = tagInput.value.trim()
  if (!tag) return
  
  if (selectedTags.value.length >= 5) {
    showToast('最多只能添加5个标签')
    return
  }
  
  if (selectedTags.value.includes(tag)) {
    showToast('标签已存在')
    return
  }
  
  selectedTags.value.push(tag)
  tagInput.value = ''
}

const addSuggestedTag = (tag) => {
  if (selectedTags.value.length >= 5) {
    showToast('最多只能添加5个标签')
    return
  }
  
  if (selectedTags.value.includes(tag)) {
    showToast('标签已存在')
    return
  }
  
  selectedTags.value.push(tag)
}

const removeTag = (index) => {
  selectedTags.value.splice(index, 1)
}

const updateSuggestedTags = (categoryId) => {
  const categoryTagsMap = {
    1: ['工资拖欠', '劳动合同', '工伤赔偿', '违法解除', '加班费', '社保问题'],
    2: ['商品质量', '虚假宣传', '退款纠纷', '售后服务', '网购维权', '消费欺诈'],
    3: ['押金纠纷', '房屋维修', '租金上涨', '提前退租', '合同违约', '房东纠纷'],
    4: ['合同纠纷', '欺诈行为', '维权经验', '法律咨询', '其他问题', '求助']
  }
  
  suggestedTags.value = categoryTagsMap[categoryId] || suggestedTags.value
}

// 检查登录状态
onMounted(() => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    router.replace('/login')
  }
})
</script>

<style scoped>
.publish-post {
  min-height: 100vh;
  background: #f7f8fa;
}

.publish-container {
  padding: 46px 0 20px 0;
}

.form-section {
  background: white;
  margin-bottom: 8px;
  padding: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
}

.image-upload {
  margin-top: 8px;
}

.uploaded-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 8px;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  object-fit: cover;
}

.image-remove {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 20px;
  height: 20px;
  background: #ff4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.image-remove .van-icon {
  color: white;
  font-size: 12px;
}

.upload-btn {
  aspect-ratio: 1;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: border-color 0.2s;
}

.upload-btn:hover {
  border-color: #1989fa;
}

.upload-btn .van-icon {
  font-size: 24px;
  color: #969799;
}

.upload-btn span {
  font-size: 12px;
  color: #969799;
}

.upload-tip {
  font-size: 12px;
  color: #969799;
  text-align: center;
}

.tags-input {
  margin-top: 8px;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 4px;
  background: #e8f4ff;
  color: #1989fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.tag-item .van-icon {
  font-size: 10px;
  cursor: pointer;
}

.suggested-tags {
  margin-top: 12px;
}

.suggested-title {
  font-size: 14px;
  color: #646566;
  margin-bottom: 8px;
}

.tag-suggestions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggested-tag {
  background: #f8f9fa;
  color: #646566;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.suggested-tag:hover {
  background: #e8f4ff;
  color: #1989fa;
}

.anonymous-tip {
  font-size: 12px;
  color: #969799;
  margin-top: 8px;
  line-height: 1.4;
}

.publish-actions {
  padding: 16px;
}

.publish-actions .van-button {
  width: 100%;
}
</style>